package com.springboot.demo.proxy.jdkproxy;

import com.springboot.demo.proxy.statics.Target;
import com.springboot.demo.proxy.statics.Target2;
import com.springboot.demo.proxy.statics.Targetln;
import com.springboot.demo.proxy.statics.Targetln2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * AOP基于动态代理
 * JDKProxy 利用反射机制
 * 有一个要求，被代理的对象必须实现一个接口
 *
 * 如果没有实现任何接M,LKMJJMKKJJJJJJJJJJJJJJJJJJJJJJJ,,,,KMM, K口，用第三方的CGlib来实现代理
 * Spring优先用JDKProxy，其次再用CGLIB
 */
public class JDKProxy implements InvocationHandler {

    private Object target;

    public Object bind(Object target){
        this.target = target;
        return  Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置增强");
        Object r = method.invoke(target,args);
        System.out.println("后置增强");
        return r;
    }

    public static void main(String[] args) {
        Targetln target = new Target();
//        target.targetMethod();
        JDKProxy jdkProxy = new JDKProxy();
        Targetln proxyObj = (Targetln) jdkProxy.bind(target);
        proxyObj.targetMethod();

        Target2 target2 = new Target2();
        Targetln2 proxyObj2 = (Targetln2)jdkProxy.bind(target2);
        proxyObj2.targetMethod();
    }
}
